package com.bjpowernode.mvc.controller;

import com.bjpowernode.common.enums.RespCode;
import com.bjpowernode.db.domain.SysUser;
import com.bjpowernode.mvc.exception.BizException;
import com.bjpowernode.mvc.model.dto.KqBeginDTO;
import com.bjpowernode.mvc.model.param.KqNotifyParam;
import com.bjpowernode.mvc.service.inter.PayService;
import com.bjpowernode.mvc.service.inter.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;

@Slf4j
@RequiredArgsConstructor
@Controller
public class PayController {

    private final PayService payService;
    private final UserService userService;

    //用户充值
    @GetMapping("/pay/begin")
    public String payBegin(@RequestParam("uid") Integer uid,
                           @RequestParam("token") String token,
                           @RequestParam("payMoney") BigDecimal payMoney,
                           Model model
    ) {

        try {
            //验证uid和token是否有效
            boolean result = payService.checkUidToken(uid, token);
            if (!result) {
                throw new BizException(RespCode.FAIL.getCode(), "请用户重新登录后再次进行充值！");
            }

            SysUser sysUser = userService.queryById(uid);
            //1、创建网银支付接口的参数
            KqBeginDTO kqBeginDTO = payService.generateApiParam(uid, token, sysUser.getPhone(), payMoney);

            //2、保存充值记录
            payService.createRechargeRecord(uid, kqBeginDTO.getOrderId(), payMoney, "KUAIQIAN");

            //3、保存订单号到Redis
            payService.saveOrderIdRedis(kqBeginDTO.getOrderId());

            //使用model传递数据
            model.addAttribute("kq", kqBeginDTO);
            return "/kq/begin";
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof BizException) {
                model.addAttribute("msg", e.getMessage());
            } else {
                model.addAttribute("msg", "请稍后重试！");
            }
            return "/kq/error";
        }
    }


    //异步通知
    @ResponseBody
    @GetMapping("/pay/notify")
    public String doNotify(KqNotifyParam kqNotifyParam) {

        log.info("接收快钱异步通知[" + kqNotifyParam.toString() + "]");
        try {
            //1、判断签名
            if (!kqNotifyParam.checkSign()) {
                log.info("商户号[" + kqNotifyParam.getMerchantAcctId() + "]-订单号[" + kqNotifyParam.getOrderId() + "]签名错误");
                throw new RuntimeException("签名错误");
            }

            //2、判断商户号MerchantAcctId
            if (!"1001214035601".equals(kqNotifyParam.getMerchantAcctId())) {
                log.info("接收的商户号：" + kqNotifyParam.getMerchantAcctId());
                throw new RuntimeException("商务号错误！");
            }

            //3、处理订单  商户订单号：orderId  订单金额：payAmount  支付结果：payResult
            String orderResult = payService.handleNotify(kqNotifyParam.getOrderId(),
                    kqNotifyParam.getPayAmount(),
                    kqNotifyParam.getPayResult());
            log.info("商户号[" + kqNotifyParam.getMerchantAcctId()
                    + "]-订单号[" + kqNotifyParam.getOrderId() + "]-结果[" + orderResult + "]");

            //4、删除redis中的已经处理的订单号  在用户充值的时候将订单号存入Redis中
            payService.deleteOrderId(kqNotifyParam.getOrderId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "<result>1</result><redirecturl>http://localhost:8080/recharge/result</redirecturl>";
    }
}
